package com.example.demo5;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
public class WsController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/send")
//    @SendToUser(destinations = "/client", broadcast = false)
    public String ws(Principal principal, String msg) {

        // 客户端订阅的地址是 /user/client
        // 服务端@SendToUser发送的代理地址是 /client， 地址将会被转化为 /user/{username}/client
        System.out.println(principal);
        System.out.println(msg);

        simpMessagingTemplate.convertAndSendToUser("yawn1", "/client", msg);
        return "TO  [ from " + principal.getName() + "] + {" + msg + "}";
    }
}
